import useUserStore from "@/store/userStore";
import { Tool } from "@/utils/tool";
import { storeToRefs } from "pinia";
import {
  createRouter,
  createWebHistory,
  NavigationGuardNext,
  RouteLocationNormalized,
  RouteLocationNormalizedLoaded,
  RouteRecordRaw,
} from "vue-router";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "login",
    redirect: "/login",

    children: [
      {
        path: "login",
        component: () => import("@/views/Login.vue"),
      },
    ],
  },
  {
    path: "/auth/oauth2.0/gitee/callback", // 这里应与Gitee回调地址中的路径部分一致
    name: "AuthCallback",
    component: () => import("@/views/AuthCallback.vue"),
  },
  {
    path: "/home",
    name: "home",
    component: () => import("@/views/home/HomeView.vue"),
  },

  {
    path: "/admin",
    name: "layout",
    children: [
      {
        path: "ebook",
        name: "AdminEbook",
        component: () => import("@/views/admin/AdminEBook.vue"),
        meta: {
          loginRequire: true,
        },
      },

      {
        path: "category",
        component: () => import("@/views/admin/AdminCategory.vue"),
        meta: {
          loginRequire: true,
        },
      },
      {
        path: "doc",
        component: () => import("@/views/admin/AdminDoc.vue"),
        meta: {
          loginRequire: true,
        },
      },

      {
        path: "user",
        component: () => import("@/views/admin/AdminUser.vue"),
        meta: {
          loginRequire: true,
        },
      },
    ],
  },

  {
    path: "/doc",
    component: () => import("@/views/home/DocView.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 在这里添加路由的导航守卫
router.beforeEach(
  (
    to: RouteLocationNormalized,
    from: RouteLocationNormalizedLoaded,
    next: NavigationGuardNext
  ) => {
    if (to.matched.some((item) => item.meta.loginRequire)) {
      const { user } = storeToRefs(useUserStore());
      if (Tool.isEmpty(user)) {
        console.log("未登录");
        next("/");
      } else {
        next();
      }
    } else {
      next();
    }
  }
);

export default router;
